<template>
  <div class="order_detail">
    <div class="order-goods">
      <van-card
        v-for="item in new_orderGoods"
        @click="
          item.giftId != undefined
            ? itemClick(item.giftId)
            : itemClick(item.goodsId)
        "
        :key="item.giftId != undefined ? item.giftId : item.id"
        :title="item.giftId != undefined ? item.giftName : item.goodsName"
        :desc="item.giftId != undefined ? '赠品' : item.specifications"
        :num="item.giftId != undefined ? item.num : item.number"
        :price="item.giftId != undefined ? null : item.price"
        :thumb="item.giftId != undefined ? item.giftImg : item.picUrl"
      >
      </van-card>

      <van-cell-group>
        <van-cell title="商品金额">
          <span class="red">{{ (orderInfo.goodsPrice * 100) | yuan }}</span>
        </van-cell>
        <van-cell title="快递费用">
          <span class="red">到付</span>
        </van-cell>
      </van-cell-group>
    </div>

    <van-cell-group style="margin-top: 20px">
      <van-cell
        icon="dingwei"
        :title="`${orderInfo.consignee}  ${orderInfo.mobile}`"
        :label="orderInfo.address"
      />
    </van-cell-group>

    <van-cell-group style="margin-top: 20px">
      <van-cell title="下单时间">
        <span>{{ orderInfo.addTime }}</span>
      </van-cell>
      <van-cell title="订单编号">
        <span>{{ orderInfo.orderSn }}</span>
      </van-cell>
      <van-cell title="订单备注">
        <span>{{ orderInfo.remark }}</span>
      </van-cell>

      <van-cell title="应付款：">
        <span class="red">{{ (orderInfo.actualPrice * 100) | yuan }}</span>
      </van-cell>
      <van-cell title="订单状态">
        <span>{{ orderInfo.orderStatusText }}</span>
      </van-cell>
      <!-- 订单动作 -->
      <van-cell>
        <!-- <van-button size="small"
                    v-if="handleOption.cancel"
                    @click="cancelOrder(orderInfo.id)"
                    style=" float:right"
                    round
                    type="danger" disabled>取消订单</van-button>
        <van-button size="small"
                    v-if="handleOption.pay"
                    @click="toPay(orderInfo.id)"
                    style=" float:right"
                    round
                    type="danger" disabled>去支付</van-button>
        <van-button size="small"
                    v-if="handleOption.delete"
                    @click="deleteOrder(orderInfo.id)"
                    style=" float:right"
                    type="danger" disabled>删除订单</van-button>
        <van-button size="small"
                    v-if="handleOption.confirm"
                    @click="confirmOrder(orderInfo.id)"
                    style=" float:right"
        type="danger" disabled>确认收货</van-button>
        <van-button
          size="small"
          v-if="handleOption.refund"
          @click="refundOrder(orderInfo.id)"
          style=" float:right"
          type="danger"
          disabled
        >退款</van-button>-->
        <van-button
          size="small"
          v-if="
            (handleOption.commit || handleOption.refund) &&
            !orderInfo.discountStatus &&
            orderInfo.discount > 0
          "
          type="danger"
          style="float: right; margin-left: 10px"
          @click.stop="modifyOrder(orderInfo.id)"
          >领取优惠</van-button
        >
        <van-button
          size="small"
          v-if="
            (handleOption.commit || handleOption.refund) &&
            orderInfo.orderType == 1
          "
          type="danger"
          style="float: right; margin-left: 10px"
          @click.stop="modifyHandset()"
          >修改定金</van-button
        >
        <van-button
          size="small"
          v-if="handleOption.refund && orderInfo.payType != 1"
          type="danger"
          style="float: right"
          @click.stop="deliveryOrder(orderInfo.id)"
          >发货</van-button
        >
      </van-cell>
    </van-cell-group>

    <van-cell-group v-if="showExp()" style="margin-top: 20px">
      <van-cell title="快递公司">
        <span>{{ orderInfo.expCode }}</span>
      </van-cell>
      <van-cell title="快递编号">
        <span>{{ orderInfo.expNo }}</span>
      </van-cell>
    </van-cell-group>
    <van-steps
      direction="vertical"
      :active="0"
      active-color="#EE3F00"
      v-if="orderInfo.expCode != '自提'"
    >
      <van-step v-if="false"
        ><!--before v-if="traces.length == 0 && showExp()" -->
        <h3>已发货，正在等待快递员揽收</h3>
        <p>{{ orderInfo.shipTime }}</p>
      </van-step>
      <van-step v-else v-for="(trace, index) in traces" :key="index">
        <h3>{{ trace.acceptStation }}</h3>
        <p>{{ trace.acceptTime }}</p>
      </van-step>
    </van-steps>
    <van-dialog
      v-model="show"
      title="发货"
      show-cancel-button
      @confirm="onDialogConfirm"
      style="width: 90%"
    >
      <div style="padding: 10px 20px">
        <van-cell-group>
          <van-field
            label="快递公司"
            required
            :readonly="true"
            clickable
            right-icon="arrow"
            :value="deliveryCom"
            placeholder="请选择快递公司"
            @click="onClick"
          />
          <van-field
            label="快递单号"
            clearable
            required
            right-icon="scan"
            v-model="deliverySn"
            placeholder="请输入快递单号"
            size="30px"
            @click-right-icon="scanKd"
          />
        </van-cell-group>
      </div>
    </van-dialog>

    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @cancel="onCancel"
        @confirm="onConfirm"
      />
    </van-popup>
    <van-dialog
      use-slot
      title="修改定金"
      v-model="showHandset"
      show-cancel-button
      @cancel="cancelHandset"
      @confirm="confirm"
    >
      <van-cell-group>
        <van-field
          label="定金金额"
          placeholder="请输入定金金额"
          v-model="handsetAmount"
        >
        </van-field>
      </van-cell-group>
    </van-dialog>
  </div>
</template>

<script>
import {
  Card,
  Field,
  SubmitBar,
  Button,
  Cell,
  CellGroup,
  Dialog,
  Step,
  Steps,
  Row,
  Col,
  Picker,
  Popup,
} from 'vant';
import _ from 'lodash';
import {
  orderDetail,
  orderDelete,
  orderConfirm,
  orderCancel,
  orderRefund,
  expressInfo,
  getWxConfig,
  dicItems,
  shipOrder,
  modify,
  handsetChange,
} from '@/api/api';

import wx from 'weixin-js-sdk';

export default {
  data() {
    return {
      show: false,
      handsetAmount: '',
      showHandset: false,
      showPicker: false,
      deliverySn: '',
      deliveryCom: '',
      currentOrderId: '',
      columns: [],
      isSubmit: false,
      isDisabled: false,
      orderInfo: {},
      orderGoods: [],
      handleOption: {},
      expressInfo: {},
      traces: [],
      new_orderGoods: [],
    };
  },
  created() {
    this.init();
  },

  methods: {
    confirm() {
      var reg = /^(:?(:?\d+.\d+)|(:?\d+))$/;
      if (!reg.test(this.handsetAmount)) {
        this.$toast('输入的金额格式不正确');
        return;
      }
      handsetChange({
        orderId: this.orderInfo.id,
        handsetAmount: this.handsetAmount,
      })
        .then((res) => {
          this.init();
          this.$toast('修改定金成功');
        })
        .catch((err) => {
          return this.$dialog.alert({ message: err.data.errmsg });
        });
    },
    cancelHandset() {
      this.showHandset = false;
    },
    modifyHandset() {
      this.showHandset = true;
    },
    // 修改订单id
    modifyOrder(id) {
      modify({ orderId: id })
        .then((res) => {
          this.init();
        })
        .catch();
    },
    // 发货
    deliveryOrder(id) {
      this.currentOrderId = id;
      this.show = true;
    },
    onDialogConfirm() {
      if (this.deliverySn == '') {
        alert('请输入快递单号');
        return;
      }
      if (this.deliveryCom == '') {
        alert('请选择快递公司');
        return;
      }
      shipOrder({
        orderId: this.currentOrderId,
        shipSn: this.deliverySn,
        shipChannel: this.deliveryCom,
      }).then((res) => {
        this.$router.go(0);
      });
    },
    scanKd() {
      let that = this;
      wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
          //var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
          // alert(JSON.stringify(res));
          // alert('11111222222');
          that.deliverySn = res.resultStr;
        },
      });
    },
    onClick() {
      //console.log('click');
      this.showPicker = true;
    },
    onCancel() {
      this.showPicker = false;
    },
    onConfirm(value) {
      this.deliveryCom = value;
      //console.log(this.deliveryCom);
      this.showPicker = false;
      if (value == '自提') {
        this.deliverySn = 'zt0001';
      }
    },
    itemClick(id) {
      this.$router.push(`/items/detail/${id}`);
    },
    showExp() {
      return _.has(this.orderInfo, 'expNo');
    },
    deleteOrder(id) {
      let that = this;
      this.$dialog
        .confirm({ message: '确定要删除该订单吗?' })
        .then(() => {
          orderDelete({ orderId: id }).then(() => {
            this.$toast('已删除订单');
            this.$router.go(-1);
          });
        })
        .catch(() => {});
    },
    cancelOrder(id) {
      this.$dialog
        .confirm({ message: '确定要取消该订单吗?' })
        .then(() => {
          orderCancel({ orderId: id }).then(() => {
            this.init();
            this.$toast('已取消该订单');
          });
        })
        .catch(() => {});
    },
    confirmOrder(id) {
      this.$dialog
        .confirm({
          message: '请确认收到货物, 确认收货后无法撤销!',
        })
        .then(() => {
          orderConfirm({ orderId: id }).then(() => {
            this.init();
            this.$toast('已确认收货');
          });
        })
        .catch(() => {});
    },
    refundOrder(id) {
      this.$dialog
        .confirm({ message: '确定要申请退款吗?' })
        .then(() => {
          orderRefund({ orderId: id }).then(() => {
            this.init();
            this.$toast('已申请订单退款');
          });
        })
        .catch(() => {});
    },
    commentOrder(id) {},
    init() {
      let orderId = this.$route.query.orderId;
      let arr = new Array();
      arr.push(orderId);
      orderDetail({ orderIds: arr }).then((res) => {
        var data = res.data.data;
        this.orderInfo = data.orderInfos[0];
        this.orderGoods = data.orderGoods;
        this.new_orderGoods = [];
        for (var i = 0; i < this.orderGoods.length; i++) {
          this.new_orderGoods.push(this.orderGoods[i]);
          if (
            this.orderGoods[i].orderGiftList !== undefined &&
            this.orderGoods[i].orderGiftList.length > 0
          ) {
            for (var j = 0; j < this.orderGoods[i].orderGiftList.length; j++) {
              this.new_orderGoods.push(this.orderGoods[i].orderGiftList[j]);
            }
          }
        }
        this.handleOption = data.orderInfos[0].handleOption;
        this.expressInfo = data.expressInfo;
        if (
          this.expressInfo != undefined &&
          data.expressInfo.traces != undefined
        ) {
          this.traces = data.expressInfo.traces;
        }
      });

      dicItems({ groupId: 'ORDER.KD.CLASS' })
        .then((res) => {
          this.columnsAll = res.data.data.list;
          if (this.columnsAll != null) {
            for (let i = 0; i < this.columnsAll.length; i++) {
              this.columns[i] = this.columnsAll[i].itemName;
            }
          }
        })
        .catch(() => {});
      getWxConfig({ url: location.href.split('#')[0] }).then((res) => {
        wx.config({
          // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          debug: false,
          // 必填，公众号的唯一标识
          appId: res.data.data.appId,
          // 必填，生成签名的时间戳
          timestamp: res.data.data.timestamp,
          // 必填，生成签名的随机串
          nonceStr: res.data.data.nonceStr,
          // 必填，签名，见附录1
          signature: res.data.data.signature,
          // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
          jsApiList: ['checkJsApi', 'scanQRCode'],
        });
      });

      wx.error(function (res) {
        alert('出错了：' + res.errMsg); //这个地方的好处就是wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
      });
      wx.ready(function () {
        wx.checkJsApi({
          jsApiList: ['scanQRCode'],
          success: function (res) {
            //alert('成功了：' + res.errMsg);
          },
        });
      });
    },
  },

  components: {
    [Dialog.name]: Dialog,
    [CellGroup.name]: CellGroup,
    [Cell.name]: Cell,
    [Button.name]: Button,
    [SubmitBar.name]: SubmitBar,
    [Card.name]: Card,
    [Field.name]: Field,
    [Row.name]: Row,
    [Col.name]: Col,
    [Step.name]: Step,
    [Steps.name]: Steps,
    [Picker.name]: Picker,
    [Popup.name]: Popup,
    [Dialog.Component.name]: Dialog.Component,
  },
};
</script>


<style lang="scss" scoped>
.order_detail {
  padding-bottom: 70px;
}
</style>
